package com.xcity.game.financial;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.xcity.db.entity.Player;

import naga.x.App;
import naga.x.game.template.TemplateService;

public class FinancialManager {
	
	private Player owner;
	private List<PlayerFinancial> financials;

	public FinancialManager(Player player, List<PlayerFinancial> financials) {
		this.owner = player;
		this.financials = filter(financials);
	}
	
	public int size() {
		return financials.size();
	}
	
	public void add(PlayerFinancial pf) {
		financials.add(pf);
	}
	
	/**
	 * 统计某个理财产品已购份数
	 * @param id
	 * @return
	 */
	public int count(int id) {
		int n = 0;
		for (int i = financials.size() - 1; i >= 0; i--) {
			PlayerFinancial pf = financials.get(i);
			if (pf.getId() == id) {
				n++;
			}
		}
		return n;
	}
	
	public List<PlayerFinancial> getFinancials() {
		return Collections.unmodifiableList(financials);
	}
	
	public boolean receiveInterest(int id) {
		List<PlayerFinancial> list = financials;
		boolean succ = false;
		if (list != null && list.size() > 0) {
			for (int i = list.size() - 1; i >= 0; i--) {
				PlayerFinancial f = list.get(i);
				if (f.getId() == id) {
					succ = f.receiveInterest(owner);
				}
			}
		}
		return succ;
	}
	
	@Override
	public String toString() {
		return JSON.toJSONString(financials);
	}

	public void init(Player player) {
		this.owner = player;
	}
	
	private List<PlayerFinancial> filter(List<PlayerFinancial> financials) {
		if (financials == null) {
			return new ArrayList<PlayerFinancial>();
		}
		int size = financials.size();
		if (size == 0) {
			return financials;
		}
		List<PlayerFinancial> result = new ArrayList<PlayerFinancial>(size);
		TemplateService ts = App.getApp().getServiceManager().get(TemplateService.class);
		for (int i = 0; i < size; i++) {
			PlayerFinancial pf = financials.get(i);
			FinancialTemplate temp = ts.get(FinancialTemplate.class, pf.getId());
			if (temp != null) {
				result.add(pf);
			}
		}
		return result;
	}

}
